import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class YamlPropertySourceLoaderUtil {

    /**
     * 从 YAML 文件加载为 Spring 的 PropertySource
     *
     * @param name   配置源的名称（任意命名）
     * @param path   classpath 下 YAML 文件路径
     * @return PropertySource
     * @throws IOException 如果加载失败抛出异常
     */
    public static PropertySource<?> loadYamlAsPropertySource(String name, String path) throws IOException {
        Yaml yaml = new Yaml();
        Resource resource = new ClassPathResource(path);

        if (!resource.exists()) {
            throw new IllegalArgumentException("YAML file not found at path: " + path);
        }

        try (InputStream input = resource.getInputStream()) {
            // 使用 SnakeYAML 加载 YAML 的内容
            Map<String, Object> yamlMap = yaml.load(input);

            // 将多层嵌套的 Map 转换成 Properties 格式
            Properties properties = new Properties();
            flattenYaml("", yamlMap, properties);

            return new PropertiesPropertySource(name, properties);
        }
    }

    /**
     * 将嵌套的 YAML 配置内容平铺为 Properties 格式
     *
     * @param prefix   当前键的前缀
     * @param source   YAML 的 Map 表示
     * @param target   平铺的 Properties
     */
    private static void flattenYaml(String prefix, Map<String, Object> source, Properties target) {
        for (Map.Entry<String, Object> entry : source.entrySet()) {
            String key = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey();
            Object value = entry.getValue();

            if (value instanceof Map) {
                // 递归处理嵌套 Map
                flattenYaml(key, (Map<String, Object>) value, target);
            } else {
                target.put(key, value);
            }
        }
    }
}
